#!/bin/sh

client_id="134daa45c8e5e61"
file="$1"

response=$(curl -H "Authorization: Client-ID ${client_id}" -H "Expect: " -F "image=@$file" https://api.imgur.com/3/image.xml 2>/dev/null)
# the "Expect: " header is to get around a problem when using this through
# the Squid proxy. Not sure if it's a Squid bug or what.
if [ $? -ne 0 ]; then
    echo "Upload failed" >&2
    exit 1
elif [ $(echo $response | grep -c "<error_msg>") -gt 0 ]; then
    echo "Error message from imgur:" >&2
    echo $response | sed -r 's/.*<error_msg>(.*)<\/error_msg>.*/\1/' >&2
    exit 1
fi

# parse the response and output our stuff
id=$(echo $response | sed -r 's/.*<id>(.*)<\/id>.*/\1/')
deletehash=$(echo $response | sed -r 's/.*<deletehash>(.*)<\/deletehash>.*/\1/')
printf "https://imgur.com/$id.jpg"
printf "Delete page: https://imgur.com/delete/$deletehash" >&2
